<template>
    <div>
      <!-- 角色列表 -->
      <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>权限管理</el-breadcrumb-item>
          <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
      <!-- 内容区 -->
        <el-card style='margin-top:20px'>
          <el-button type="primary" @click="addrole">添加角色</el-button>

          <!-- 添加角色对话框 -->
          <el-dialog
            title="添加角色"
            :visible.sync="addVis"
            width="30%">

            <el-form :model="addRolesForm" :rules="addRoles" ref="addRolesForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="addRolesForm.roleName"></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="addRolesForm.roleDesc"></el-input>
              </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
              <el-button @click="addback">取 消</el-button>
              <el-button type="primary" @click="sureadd">确 定</el-button>
            </span>
          </el-dialog>
          <!-- 列表 -->
          <el-table
            :data="tableData"
            border
            style="width: 100%;margin-top:20px">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- {{scope.row}} -->
                <!-- 一级权限 -->
                <el-row v-for ='(item1,i1) in scope.row.children' :key="item1.id"  :class="i1>0 ?'row1':''">
                  <el-col  :span="5">
                    <el-tag closable @close = 'tagclose1(scope.row,item1)'>
                      {{item1.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                    <!-- 二级权限 -->
                    <el-row  v-for ='(item2,i2) in item1.children' :key="item2.id" :class="i2>0 ?'row2':''">
                      <el-col :span="5">
                        <el-tag closable type="success" @close = 'tagclose2(scope.row,item2)'>
                          {{item2.authName}}
                        </el-tag>
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                      <el-col :span="19">
                        <!-- 三级权限 -->
                            <el-tag closable type="danger" v-for ='(item3,i3) in item2.children' :key="item3.id" @close = 'tagclose3(scope.row,item3)'>
                              {{item3.authName}}
                            </el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column
              label="角色名称"
              prop="roleName">
            </el-table-column>
            <el-table-column
              label="角色描述"
              prop="roleDesc">
            </el-table-column>
            <el-table-column
              label="操作">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="修改角色" placement="top-start" :enterable="false">
                <el-button type="warning" icon="el-icon-edit" @click="modRoles(scope.row.id)" style="margin-right:10px"></el-button>
                </el-tooltip>
                  <!-- 修改角色对话框 -->
                  <el-dialog
                    title="修改角色"
                    :visible.sync="modVis"
                    width="30%">

                    <el-form :model="modRolesForm" :rules="addRoles" ref="modRolesForm" label-width="100px" class="demo-ruleForm">
                      <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="modRolesForm.roleName"></el-input>
                      </el-form-item>
                      <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="modRolesForm.roleDesc"></el-input>
                      </el-form-item>
                    </el-form>

                    <span slot="footer" class="dialog-footer">
                      <el-button @click="modback">取 消</el-button>
                      <el-button type="primary" @click="modadd">确 定</el-button>
                    </span>
                  </el-dialog>
                
                <el-tooltip class="item" effect="dark" content="删除角色" placement="top-start" :enterable="false">
                <el-button type="danger" icon="el-icon-delete" @click="opendelete(scope.row.id)"></el-button>
                </el-tooltip>
                <!-- 分配权限 -->
                <el-tooltip class="item" effect="dark" content="分配权限" placement="top-start" :enterable="false">
                <el-button type="primary" icon="el-icon-share" @click="open(scope.row)"></el-button>
                </el-tooltip>
                  <el-dialog
                    title="提示"
                    :visible.sync="dialogVisible"
                    width="50%">
                    <!-- 树形控件 -->
                    <el-tree
                      :data="roles"
                      show-checkbox
                      default-expand-all
                      node-key="id"
                      ref="treedata"
                      :default-checked-keys="keysid"
                      :props="defaultProps">
                    </el-tree>
                    <span slot="footer" class="dialog-footer">
                      <el-button @click="treeclose">取 消</el-button>
                      <el-button type="primary" @click="treesure">确 定</el-button>
                    </span>
                  </el-dialog>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
    </div>
</template>

<script>
export default {
    data() {
        return {
          tableData:[],
          dialogVisible :false,
          addVis:false,
          modVis:false,
          roles:[],
          defaultProps: {
          children: 'children',
          label: 'authName'
          },
          keysid:[],
          roleId:'',
          addRolesForm:{
            roleName:'',
            roleDesc:''
          },//添加角色列表
          addRoles: {
            roleName: [
              { required: true, message: '请输入角色名称', trigger: 'blur' },
              { min: 2, max: 5, message: '长度在2 到 5 个字符', trigger: 'blur' }
                  ],
            roleDesc: [
              { required: true, message: '请输入角色描述', trigger: 'blur' },
              { min: 3, max: 10, message: '长度在 3 到 10个字符', trigger: 'blur' }
                  ]
            },
            //修改角色
            modRolesForm:{
              roleName:"",
              roleDesc:'',
              id:''
             }
        };
    },
    created() {
      this.goRolesData()
    },
    mounted() {

    },
    methods: {
      //请求角色及对应权限列表
      async goRolesData(){
        const {data:ref} = await this.$http.get('roles')
        console.log(ref);
        this.tableData = ref.data
      },
      //删除对应权限
       tagclose1(role,item1){//一级
        this.$confirm('是否确定取消该权限？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async() => {
          const {data:ref} = await this.$http.delete('roles/'+role.id+'/rights/'+item1.id)
          console.log(ref)
          if(ref.meta.status =! 200) return this.$message.error('取消权限失败')
          this.$message.success('取消权限成功')
          role.children = ref.data//局部刷新
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        })
        },
       tagclose2(role,item2){//一级
        this.$confirm('是否确定取消该权限？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async() => {
          const {data:ref} = await this.$http.delete('roles/'+role.id+'/rights/'+item2.id)
          console.log(ref)
          if(ref.meta.status =! 200) return this.$message.error('取消权限失败')
          this.$message.success('取消权限成功')
          role.children = ref.data//局部刷新
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        })
          },
       tagclose3(role,item3){//一级
        this.$confirm('是否确定取消该权限？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async() => {
          const {data:ref} = await this.$http.delete('roles/'+role.id+'/rights/'+item3.id)
          console.log(ref)
          if(ref.meta.status =! 200) return this.$message.error('取消权限失败')
          this.$message.success('取消权限成功')
          role.children = ref.data//局部刷新
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        })
        },
      //修改权限
      async open(data){
        this.dialogVisible = true;
        // console.log(data);
        const {data:ref} = await this.$http.get('rights/tree')
        console.log(ref);
        if(ref.meta.status =!200) return this.$message.error('获取权限失败')
        this.roles = ref.data
        this.goarr(data,this.keysid)
        this.roleId = data.id
      },
      //查找三级权限的id，并添加到数组
      goarr(node,arr){
        // console.log(node);
        if(!node.children){//直到node里面没有childern时，把此内容的id加到数组arr中
          return arr.push(node.id)
        }
        node.children.forEach(item => {//把node的内容全部循环出来，如果内容里面还有children，继续循环出来
          this.goarr(item,arr)
        });
        // console.log(arr);
      },
      //确定修改并提交
      async treesure(){
        const keys = [...this.$refs.treedata.getHalfCheckedKeys(),...this.$refs.treedata.getCheckedKeys()]
        const rightId =keys.join(',')
        const {data:ref} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:rightId})
        console.log(ref);
        if(ref.meta.status =!200) return this.$message.error('更新失败')
        this.$message.success('分配权限成功')
        this.dialogVisible = false
        await this.$http.get('rights/tree')
        this.goRolesData()
      },
      //取消修改
      treeclose(){
        this.dialogVisible = false
        this.keysid = []
        this.$router.push('/Roles')
      },
      //添加角色
      addrole(){
        this.addVis = true
      },
      // 提交添加角色
      sureadd(){
        this.$refs.addRolesForm.validate(async valid =>{
          if(!valid) return
          const {data:ref} = await this.$http.post('roles',this.addRolesForm)
          if(ref.meta.status =! 200) return this.$message.error('创建角色失败')
          this.$message.success('创建角色成功')
          this.addVis = false
          this.goRolesData()
        })
      },
      addback(){
        this.addVis = false
        this.$refs.addRolesForm.resetFields()
      },
      //是否删除角色弹框
      opendelete(id) {
        this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async () => {
          const {data:res} = await this.$http.delete('roles/'+id)
          if(res.meta.status =! 200) return this.$message.error('删除角色失败')
          this.$message.success('删除角色成功')
          this.goRolesData()

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      //修改角色弹窗
      async modRoles(id){
        console.log(id);
        this.modVis =true;
        const {data:res} = await this.$http.get('roles/'+id)
        if(res.meta.status =! 200) return this.$message.error('获取角色信息失败')
        this.modRolesForm.roleName = res.data.roleName
        this.modRolesForm.roleDesc = res.data.roleDesc
        this.modRolesForm.id = id
      },
      //提交修改角色
      modadd(){
        this.$refs.modRolesForm.validate(async valid =>{
          if(!valid) return
          const {data:res} = await this.$http.put(`roles/${this.modRolesForm.id}`,{roleName:this.modRolesForm.roleName,roleDesc:this.modRolesForm.roleDesc})
          if(res.meta.status =! 200) return this.$message.error('修改角色失败')
          this.$message.success('修改角色信息成功')
          this.modVis = false
          this.goRolesData()
        })
      },
      modback(){
        this.modVis = false
        this.$refs.modRolesForm.resetFields()
      }
    }
};
</script>

<style scoped>
.row1{
  border-top:1px solid #f6f6f6;
  display: flex;
  align-items: center;
}
.row2{
  border-top:1px solid #f6f6f6;
  display: flex;
  align-items: center;
}
.el-tag{
  margin: 10px;
}

</style>
